package kayao.client.network;

import java.net.DatagramPacket;

import android.os.SystemClock;
import kayao.common.KayaoValues;
import kayao.common.NetworkUtils;

public class SynchronizedTime {
	private static long mTimestamp1;
	private static long mTimestamp2;
	private static long mDelay;
	private static long mOffset;
	private static final boolean mDebug = false;

	private SynchronizedTime() {}
	
	public static void askForTime(DatagramPacket sendPacket) {
		byte[] sendData = new byte[5];
		NetworkUtils.insertIntToByteArray(sendData, 0, KayaoValues.MAGIC_NUMBER);
		sendData[4] = KayaoValues.WHAT_TIME_IS_IT_MESSAGE;
		sendPacket.setData(sendData);
		mTimestamp1 = SystemClock.uptimeMillis();
	}

	public static void setTime(DatagramPacket receivePacket) {
		mTimestamp2 = SystemClock.uptimeMillis();
		mDelay = (mTimestamp2-mTimestamp1)/2;

		// Process the received packet
		byte[] receiveData = receivePacket.getData();
		int index = 0;
		// Get message id
		int msgID = NetworkUtils.unsignedByteToInt(receiveData[index]);
		if (msgID != KayaoValues.TIME_IS_MESSAGE){
			System.out.println("(SynchronizedTime) ERROR: Expected reply on Time request");
		}
		index++;
		int uptime = NetworkUtils.insertByteArrayToInt(receiveData, index);
		mOffset = uptime - mTimestamp2 + mDelay;
		if (mDebug){
			System.out.println("DEBUG PRINTOUT FROM SynchronizedTime");
			System.out.println("Uptime received from server: "+uptime);
			System.out.println("Timestamp2: "+mTimestamp2+" Timestamp1: "+mTimestamp1);
			System.out.println("Delay: "+mDelay);
			System.out.println("Offset: "+mOffset);
		}
	}
	
	public static int getTime(){
		return (int)(SystemClock.uptimeMillis()+mOffset);
	}

	public static String convertUptime(long uptime) {
		String format = String.format("%%0%dd", 2);
		uptime = uptime / 1000;
		String seconds = String.format(format, uptime % 60);
		String minutes = String.format(format, (uptime % 3600) / 60);
		String hours = String.format(format, uptime / 3600);
		String time =  hours + ":" + minutes + ":" + seconds;
    	return time;  
    }

}
